//
//  Toast.swift
//  JavaShop
//
//  Created by LDD on 2018/6/4.
//  Copyright © 2018年 LDD. All rights reserved.
//  @Note  Toast功能代理类
//

import Foundation
import Toast_Swift
import Then

class ToastAgent {
    
    /// 单例
    public static let shared = ToastAgent()
    
    
    /// 显示Toast文字
    ///
    /// - Parameters:
    ///   - text: 文本内容
    ///   - sec: 显示持续时间
    public func showText(text : String ,interval :TimeInterval){
        keyWindow()?.hideToast()
        keyWindow()?.makeToast(text, duration: interval, position: .bottom)
    }
    
    
    /// 显示Toast文字 默认实现两秒
    ///
    /// - Parameter text: 显示文字
    public func showText(text :String){
        keyWindow()?.hideToast()
        keyWindow()?.makeToast(text, duration: 1.0, position: .center)
    }
    
    
    /// 显示加载框
    ///
    /// - Parameter touchOutSideRemove: 是否点击边界移除移除
    public func beginLogin(touchOutSideRemove : Bool = false){
        
        let parent = UIView.init(frame: CGRect(x: 0, y: 0, width: CPScreenWidth, height: CPScreenHeight)).then { (parent) in
            parent.backgroundColor = UIColor.clear
        }
        
        
        let imageview = UIImageView().then { (imageview) in
            imageview.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width/15, height: UIScreen.main.bounds.width/15)
            imageview.image = UIImage.init(named: "javashop_icon_common_load")
            imageview.center = parent.center
            let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z") // 让其在z轴旋转
            rotationAnimation.toValue = NSNumber(value: Double.pi * 2.0) // 旋转角度
            rotationAnimation.duration = 0.6 // 旋转周期
            rotationAnimation.isCumulative = true // 旋转累加角度
            rotationAnimation.repeatCount = 100000 // 旋转次数
            imageview.layer.add(rotationAnimation, forKey: "rotationAnimation")
        }
        let lable = UILabel().then { (lable) in
            lable.font = UIFont.systemFont(ofSize: 10)
            lable.backgroundColor = UIColor.clear
            lable.textColor = UIColor.white
            lable.numberOfLines = 0
            lable.textAlignment = .center
            lable.frame = CGRect.init(x: 0, y: 0,width:UIScreen.main.bounds.width/25, height: UIScreen.main.bounds.width/25)
            lable.center = parent.center
//            lable.text="JS"
            lable.textColor = CPHEXColor(value: 0xcccccc)
        }
        parent.addSubview(imageview)
        parent.addSubview(lable)
        if touchOutSideRemove {
            parent.setOnClickListener(target: self, action: #selector(hide))
        }
        keyWindow()?.showToast(parent, duration: 100000)
    }
    
    
    /// 隐藏所有吐司
    @objc func hide(){
        keyWindow()?.hideAllToasts()
    }

}
